package com.huluobo.a2207douyindemo.shop;

import android.content.Intent;
import android.util.Log;

import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2207douyindemo.R;
import com.huluobo.a2207douyindemo.adapter.ShopAdapter;
import com.huluobo.a2207douyindemo.databinding.ActivityShopBinding;
import com.huluobo.base.mvvm.BaseMVVMActivity;

public class ShopActivity extends BaseMVVMActivity<ActivityShopBinding, ShopViewModel> {

    private ShopAdapter shopAdapter;

    @Override
    protected void initData() {
        vm.getAllGoods(0, 1, 10);
        vm.getAllGoodsSuccess.observe(this, shopBeanResult -> {
            if (shopBeanResult.getCode() == 200) {
                shopAdapter.getData().clear();
                shopAdapter.getData().addAll(shopBeanResult.getData());
                shopAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showLong(shopBeanResult.getMessage());
            }
        });

        vm.getAllGoodsFailed.observe(this, s -> {
            Log.i("TagA", "获取商品列表失败:" + s);
        });

        vm.addToCartSuccess.observe(this, commonBeanResult -> {
            ToastUtils.showLong(commonBeanResult.getMessage());
        });

        vm.addToCartFailed.observe(this, s -> {
            Log.i("TagA", "添加购物车失败:" + s);
        });
    }

    @Override
    protected void initView() {
        binding.shopRv.setLayoutManager(new GridLayoutManager(this, 2));
        shopAdapter = new ShopAdapter();
        binding.shopRv.setAdapter(shopAdapter);

        shopAdapter.addChildClickViewIds(R.id.item_shop_add_to_cart_btn);
        shopAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.item_shop_add_to_cart_btn) {
                vm.addToCart(1, shopAdapter.getData().get(position).getId());
            }
        });

        binding.shopFloatingBtn.setOnClickListener(v -> {
            Intent intent = new Intent(this, CartActivity.class);
            startActivity(intent);
        });
    }

    @Override
    protected Class<ShopViewModel> getViewModel() {
        return ShopViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop;
    }
}